package mylab.utils.common;

import java.security.SecureRandom;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

/**
 * 数据工具类
 */
@Slf4j
@UtilityClass
public class NumberUtil extends cn.hutool.core.util.NumberUtil {

    private String[] hanArr = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    private String[] unitArr = {"十", "百", "千", "万", "十", "白", "千", "亿", "十", "百", "千"};

    /**
     * String转成int的值， 若无法转换，默认返回0
     */
    public int toInt(String strNumber) {
        return toInt(strNumber, 0);
    }

    public int toInt(String strNumber, int defaultValue) {
        if (CharSequenceUtil.isEmpty(strNumber)) {
            return defaultValue;
        }
        int id;

        try {
            id = Integer.parseInt(strNumber);
        } catch (NumberFormatException e) {
            log.error(e.getMessage());
            return defaultValue;
        }
        return id;
    }

    /**
     * String转成long的值， 若无法转换，默认返回0
     */
    public long toLong(String strNumber) {
        return toLong(strNumber, 0);
    }

    public long toLong(String strNumber, long defaultValue) {
        if (CharSequenceUtil.isEmpty(strNumber)) {
            return defaultValue;
        }
        long ret;
        try {
            ret = Long.parseLong(strNumber);
        } catch (NumberFormatException e) {
            log.error(e.getMessage());
            return defaultValue;
        }

        return ret;
    }

    /**
     * String转成double的值， 若无法转换，默认返回0.00
     */
    public double toDouble(String strNumber) {
        return toDouble(strNumber, 0.00);
    }

    public double toDouble(String strNumber, double defaultValue) {
        if (CharSequenceUtil.isEmpty(strNumber)) {
            return defaultValue;
        }
        double ret;
        try {
            ret = Double.parseDouble(strNumber);
        } catch (NumberFormatException e) {
            log.error(e.getMessage());
            return defaultValue;
        }

        return ret;
    }

    /**
     * 将整数转成中文表示
     */
    public String toChineseNum(int number) {
        String numStr = String.valueOf(number);
        StringBuilder result = new StringBuilder();
        int numLen = numStr.length();
        for (int i = 0; i < numLen; i++) {
            int num = numStr.charAt(i) - 48;
            if (i != numLen - 1 && num != 0) {
                result.append(hanArr[num]).append(unitArr[numLen - 2 - i]);
                if (number >= 10 && number < 20) {
                    result = new StringBuilder(result.substring(1));
                }
            } else {
                if (!(number >= 10 && number % 10 == 0)) {
                    result.append(hanArr[num]);
                }
            }
        }
        return result.toString();
    }


    /**
     * 获取一个属于[min, max)中的随机数
     */
    public int random(int min, int max) {
        return new SecureRandom().nextInt(max - min) + min;
    }

}
